import React, { useEffect, useState } from "react";
import {
  Navbar,
  NavbarBrand,
  NavbarMenuToggle,
  NavbarMenu,
  NavbarMenuItem,
  NavbarContent,
  NavbarItem,
  Link,
  Button,
  Avatar,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  User,
  Tooltip,
} from "@nextui-org/react";
import { icons } from "./icons";
import { withRouter, useRouter } from "next/router";
import { useGlobalState } from "@/hooks/useGlobalState";
import { Person } from "@mui/icons-material";
import { useHttp } from "@/hooks";
import { LocalCache } from "@/utils/storage";
import { useActions } from "@/hooks/useActions";
import useMounted from "@/hooks/useMounted";
import { eventBus } from "@/utils/event";

export default function TopNav() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const menuItems = [
    { text: "Apps", path: "/apps" },
    { text: "Configs", path: "/configs" },
    { text: "Users", path: "/users" },
    { text: "Log Out", path: "/api/logout" },
  ];
  const router = useRouter();
  const { http } = useHttp();
  const { clearUserInfo, setUserInfo } = useActions();

  const goHome = () => {
    router.push("/");
  };
  const handleLogout = async (silent = false) => {
    const res = await http.get("/api/logout", {}, { isWaitTips: true, silent });
    if (res?.success) {
      clearUserInfo({});
      router.push("/");
    }
  };

  const listenGlobalEvents = () => {
    eventBus.on("logout", handleLogout);
    eventBus.on("userinfo", getUserInfo);
  };

  const unlistenGlobalEvents = () => {
    eventBus.off("logout", handleLogout);
    eventBus.off("userinfo", getUserInfo);
  };

  const getUserInfo = async (silent = false) => {
    const res = await http.get(
      "/api/user/info",
      {},
      { isWaitTips: true, silent }
    );
    if (res?.success) {
      setUserInfo(res.data);
    }
  };

  useMounted(() => {
    const LCache = LocalCache();
    const user = LCache.get<UserInfo>("user");
    user?.id && getUserInfo(true);
    listenGlobalEvents();
  }, unlistenGlobalEvents);

  const handleDropdownItemClick = (key: string | number) => {
    if (key === "logout") {
      handleLogout();
    } else if (key === "settings") {
      router.push("/user/profile");
    }
  };

  const userInfo = useGlobalState("user", "userInfo");
  // console.log("🚀 ~ TopNav ~ userInfo:", userInfo);

  const TooltipCmp = userInfo.name
    ? Tooltip
    : // @ts-ignore
      ({ children, ...props }) => <div {...props}>{children}</div>;

  return (
    <Navbar
      // isBordered
      isMenuOpen={isMenuOpen}
      onMenuOpenChange={setIsMenuOpen}
      className="topnav w-full h-65 flex-grow-0 flex-shrink-0 bg-[#cce4fe]"
      classNames={{
        item: ["data-[active=true]:!font-normal"],
        wrapper: ["!max-w-none"],
      }}
    >
      <NavbarContent className="sm:hidden" justify="start">
        <NavbarMenuToggle />
      </NavbarContent>

      <NavbarContent className="sm:hidden pr-3" justify="center">
        <NavbarBrand>
          {icons.setting}
          <p className="font-bold text-lg text-primary ml-1">ConfigCenter</p>
        </NavbarBrand>
      </NavbarContent>

      <NavbarContent className="hidden sm:flex gap-4" justify="center">
        <NavbarBrand className="cursor-pointer" onClick={goHome}>
          {icons.setting}
          <p className="text-lg text-primary ml-1 font-100">ConfigCenter</p>
        </NavbarBrand>
        {/* <NavbarItem isActive={router.pathname === "/apps"} className="ml-8">
          <Link
            color={router.pathname === "/apps" ? "primary" : "foreground"}
            href="/apps"
          >
            Apps
          </Link>
        </NavbarItem> */}
        {/* <NavbarItem isActive={router.pathname === "/configs"}>
          <Link
            color={router.pathname === "/configs" ? "primary" : "foreground"}
            href="/configs"
          >
            Configs
          </Link>
        </NavbarItem> */}

        {/* {userInfo?.role === 1 && (
          <NavbarItem isActive={router.pathname === "/users"}>
            <Link
              color={router.pathname === "/users" ? "primary" : "foreground"}
              href="/users"
            >
              Users
            </Link>
          </NavbarItem>
        )} */}
      </NavbarContent>

      <NavbarContent as="div" justify="end">
        <TooltipCmp offset={15} content={userInfo.name ?? ""}>
          <div className="dropdown-wrapper">
            <Dropdown placement="bottom-end">
              <DropdownTrigger>
                <User
                  name=""
                  style={{ cursor: "pointer" }}
                  avatarProps={{
                    isBordered: true,
                    className: "transition-transform",
                    color: "primary",
                    name: userInfo.name ?? "",
                    size: "sm",
                    src: userInfo.avatarData
                      ? `${userInfo.avatarData}`
                      : undefined,
                    fallback: !(userInfo.avatarData || userInfo.name) ? (
                      <Person />
                    ) : undefined,
                  }}
                />
              </DropdownTrigger>
              <DropdownMenu
                aria-label="Profile Actions"
                variant="flat"
                onAction={handleDropdownItemClick}
              >
                <DropdownItem key="settings">My Settings</DropdownItem>
                <DropdownItem key="logout" color="danger">
                  Log Out
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </TooltipCmp>
      </NavbarContent>

      <NavbarMenu>
        {menuItems.map((menuItem, index) => (
          <NavbarMenuItem key={`${menuItem}-${index}`}>
            <Link
              className="w-full"
              color={index === menuItems.length - 1 ? "danger" : "foreground"}
              href={menuItem.path}
              size="lg"
            >
              {menuItem.text}
            </Link>
          </NavbarMenuItem>
        ))}
      </NavbarMenu>
    </Navbar>
  );
}
